import {Component, OnInit, ViewChild} from '@angular/core';
import {DeviceCheckService} from './device-check.service';
import {DatePipe} from '@angular/common';
import {NzDatePickerComponent} from 'ng-zorro-antd/date-picker';
import {NzMessageService} from 'ng-zorro-antd/message';
import {PermissionService} from '../../../service/permission.service';
import {UsedStoreZservice} from '../used-store-zservice';
import {NzModalService} from 'ng-zorro-antd/modal';
import {UsedStorePService} from '../used-store-p.service';

@Component({
  selector: 'app-device-check',
  templateUrl: './device-check.component.html',
  styleUrls: ['./device-check.component.scss']
})
export class DeviceCheckComponent implements OnInit {
  // 待验收
  waitCheck = {
    query: {
      equipmentCode: '',
      startTime: '',
      endTime: '',
      modelName: '',
      source: '',
      page: 1,
      pageSize: 10,
    },
    tableData: {
      records: [],
      type: [],
      date: [],
      total: 0,
      checked: false,
      indeterminate: false,
      setOfCheckedId: new Set<number>(),
    }
  };
  detailModal = {
    visible: false,
    id: '',
    phoneCode: '',
    net: '',
    typeName: '',
    modelName: '',
    finalPrice: '',
    checkNote: '',
    store: '',
    colourName: '',
    colourNameB: '',
    img: [],
  };
  // 已验收
  checked = {
    query: {
      equipmentCode: '',
      startTime: '' as any,
      endTime: '' as any,
      type: '',
      source: '',
      page: 1,
      pageSize: 10,
    },
    tableData: {
      records: [],
      total: 0,
    }
  };

  // 统计
  statistics = {
    query: {
      startTime: '' as any,
      endTime: '' as any,
      source: '',
    },
    tableData: {
      records: [],
      total: 0,
      totalAcceptCount: 0,
      totalCount: 0,
    }
  };
  OCCUPYSTATUS = [
    '未占用',
    '回收占用',
    '商城占用',
    '出库单占用',
    '二手售后占用',
  ];
  disabledStartDateChecked = (startValue: Date): boolean => {
    if (!startValue || !this.checked.query.endTime) {
      return false;
    }
    return new Date(startValue).getTime() > new Date(this.checked.query.endTime).getTime() ||
      startValue.getTime() < new Date(this.checked.query.endTime).getTime() - 1000 * 3600 * 24 * 62 + 3600000;
  };

  disabledEndDateChecked = (endValue: Date): boolean => {
    if (!endValue || !this.checked.query.startTime) {
      return false;
    }
    return new Date(endValue).getTime() + (1000 * 3600 * 16) <= new Date(this.checked.query.startTime).getTime() ||
      new Date(endValue).getTime() > new Date(this.checked.query.startTime).getTime() + 1000 * 3600 * 24 * 62 + 3600000;
  };

  disabledStartDateStatistics = (startValue: Date): boolean => {
    if (!startValue || !this.statistics.query.endTime) {
      return false;
    }
    return new Date(startValue).getTime() > new Date(this.statistics.query.endTime).getTime() ||
      startValue.getTime() < new Date(this.statistics.query.endTime).getTime() - 1000 * 3600 * 24 * 62 + 3600000;
  };

  disabledEndDateStatistics = (endValue: Date): boolean => {
    if (!endValue || !this.statistics.query.startTime) {
      return false;
    }
    return new Date(endValue).getTime() + (1000 * 3600 * 16) <= new Date(this.statistics.query.startTime).getTime() ||
      new Date(endValue).getTime() > new Date(this.statistics.query.startTime).getTime() + 1000 * 3600 * 24 * 62 + 3600000;
  };

  /**
   * ----------------------------------------------------------------
   * 修改库位 Modal
   * ----------------------------------------------------------------
   */
  isKwVisible = false;
  locationModalObj = {
    libraryId: '',
    isMerge: false // 修改库位: false, 修改库位并二手占用: true
  };
  locationOptions: Array<any> = []; // 库位options
  submitKwLoading = false;

  constructor(
    private deviceCheckService: DeviceCheckService,
    private datePipe: DatePipe,
    public permissionService: PermissionService,
    private nzMessageService: NzMessageService,
    private usedStoreZservice: UsedStoreZservice,
    private modal: NzModalService,
    private usedStorePService: UsedStorePService
  ) {
  }

  ngOnInit(): void {
    this.loadLocationOptions(); // 库位List
    this.initCheckedTime();
    this.initStatisticsTime();

    this.getWaitCheckTableList();
    this.getCheckedTableList();
    this.getStatisticsTableList();
  }

  // 查询库位List
  async loadLocationOptions() {
    let params = {
      page: 1,
      pageSize: 9999
    };
    const {code, data}: any = await this.usedStoreZservice.recycleLibraryList(params);
    if (code === 0) {
      this.locationOptions = data.records;
    }
  }

  initCheckedTime() {
    this.checked.query.startTime = this.datePipe.transform(new Date().getMonth() === 0 ? new Date().getFullYear() - 1 + '-12-01' :
      // @ts-ignore
      new Date().getFullYear() + '-' + new Date().getMonth() + '-01', 'yyyy-MM-dd');
    this.checked.query.endTime = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
  }

  initStatisticsTime() {
    this.statistics.query.startTime = this.datePipe.transform(new Date().getMonth() === 0 ? new Date().getFullYear() - 1 + '-12-01' :
      // @ts-ignore
      new Date().getFullYear() + '-' + new Date().getMonth() + '-01', 'yyyy-MM-dd');
    this.statistics.query.endTime = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
  }

  waitCheckTimeClick(time: any) {
    this.waitCheck.query.startTime = time;
    this.waitCheck.query.endTime = time;
    this.waitCheck.query.page = 1;
    this.getWaitCheckTableList();
  }

  waitCheckTypeClick(type: any) {
    this.waitCheck.query.modelName = type;
    this.waitCheck.query.page = 1;
    this.getWaitCheckTableList();
  }

  // 待验收
  getWaitCheckTableList() {
    // clinchBeginTime    成交入库开始时间（年月日）
    // clinchEndTime    成交入库结束时间（年月日）
    // page    必填
    // pageSize    必填
    // equipmentCode    编码（模糊查询）
    // source    来源 0回收 1重新入库
    // modelName    机型（字符串逗号分隔）
    this.waitCheck.tableData = {
      records: [],
      type: [],
      date: [],
      total: 0,
      checked: false,
      indeterminate: false,
      setOfCheckedId: new Set<number>(),
    };
    this.deviceCheckService.getWaitCheckList({
      clinchBeginTime: this.datePipe.transform(this.waitCheck.query.startTime, 'yyyy-MM-dd'),
      clinchEndTime: this.datePipe.transform(this.waitCheck.query.endTime, 'yyyy-MM-dd'),
      page: this.waitCheck.query.page,
      pageSize: this.waitCheck.query.pageSize,
      equipmentCode: this.waitCheck.query.equipmentCode,
      source: this.waitCheck.query.source,
      modelName: this.waitCheck.query.modelName,
    }).then((res: any) => {
      if (res.code === 0) {
        this.waitCheck.tableData.records = res.data.records;
        this.waitCheck.tableData.total = res.data.total;
        this.waitCheck.tableData.date = res.data.date;
        this.waitCheck.tableData.type = res.data.machines;
      }
    });
  }

  // 已验收
  getCheckedTableList() {
    this.deviceCheckService.getCheckedList({
      acceptanceBeginTime: this.datePipe.transform(this.checked.query.startTime, 'yyyy-MM-dd'),
      acceptanceEndTime: this.datePipe.transform(this.checked.query.endTime, 'yyyy-MM-dd'),
      page: this.checked.query.page,
      pageSize: this.checked.query.pageSize,
      equipmentCode: this.checked.query.equipmentCode,
      source: this.checked.query.source,
    }).then((res: any) => {
      if (res.code === 0) {
        this.checked.tableData.records = res.data.records;
        this.checked.tableData.total = res.data.total;
      }
    });
  }

  // 统计
  getStatisticsTableList() {
    if (!this.statistics.query.startTime || !this.statistics.query.endTime) {
      this.nzMessageService.warning('请选择验收时间');
      return;
    }
    this.deviceCheckService.getStatisticsList({
      acceptanceBeginTime: this.datePipe.transform(this.statistics.query.startTime, 'yyyy-MM-dd'),
      acceptanceEndTime: this.datePipe.transform(this.statistics.query.endTime, 'yyyy-MM-dd'),
      source: this.statistics.query.source,
    }).then((res: any) => {
      if (res.code === 0) {
        this.statistics.tableData.records = res.data.count;
        this.statistics.tableData.totalAcceptCount = res.data.totalAcceptCount;
        this.statistics.tableData.totalCount = res.data.totalCount;
      }
    });
  }

  queryBtn(type: 'waitCheck' | 'checked' | 'statistics') {
    if (type === 'waitCheck') {
      this.waitCheck.query.page = 1;
      this.getWaitCheckTableList();
    }
    if (type === 'checked') {
      this.checked.query.page = 1;
      this.getCheckedTableList();
    }
    if (type === 'statistics') {
      this.getStatisticsTableList();
    }
  }

  resetCondition(type: 'waitCheck' | 'checked' | 'statistics') {
    if (type === 'waitCheck') {
      this.waitCheck.query = {
        equipmentCode: '',
        startTime: '',
        endTime: '',
        modelName: '',
        source: '',
        page: 1,
        pageSize: 10,
      };
      this.getWaitCheckTableList();
    }
    if (type === 'checked') {
      this.checked.query = {
        equipmentCode: '',
        startTime: '',
        endTime: '',
        type: '',
        source: '',
        page: 1,
        pageSize: 10,
      };
      this.initCheckedTime();
      this.getCheckedTableList();
    }
    if (type === 'statistics') {
      this.statistics.query = {
        startTime: '',
        endTime: '',
        source: '',
      };
      this.initStatisticsTime();
      this.getStatisticsTableList();
    }
  }

  onPageIndexChangeWaitCheck(index: number) {
    this.waitCheck.query.page = index;
    this.getWaitCheckTableList();
  }

  onPageSizeChangeWaitCheck(pageSize: number) {
    this.waitCheck.query.pageSize = pageSize;
    this.getWaitCheckTableList();
  }

  onPageIndexChangeChecked(index: number) {
    this.checked.query.page = index;
    this.getCheckedTableList();
  }

  onPageSizeChangeChecked(pageSize: number) {
    this.checked.query.pageSize = pageSize;
    this.getCheckedTableList();
  }

  onAllCheckedWaitCheck(checked: boolean): void {
    this.waitCheck.tableData.records
      // // @ts-ignore
      // .filter(({disabled, status}) => !disabled && status !== 4)
      // @ts-ignore
      .forEach(({id}) => this.updateCheckedSetWaitCheck(id, checked));
    this.refreshCheckedStatusWaitCheck();
  }

  refreshCheckedStatusWaitCheck(): void {
    // @ts-ignore
    const listOfEnabledData = this.waitCheck.tableData.records;
    // @ts-ignore
    this.waitCheck.tableData.checked = listOfEnabledData.every(({id}) => this.waitCheck.tableData.setOfCheckedId.has(id));
    // @ts-ignore
    this.waitCheck.tableData.indeterminate = listOfEnabledData.some(({id}) => this.waitCheck.tableData.setOfCheckedId.has(id)) && !this.waitCheck.tableData.checked;
  }

  onItemChecked(id: number, checked: boolean): void {
    console.log(id, checked);
    this.updateCheckedSetWaitCheck(id, checked);
    this.refreshCheckedStatusWaitCheck();
  }

  updateCheckedSetWaitCheck(id: number, checked: boolean): void {
    if (checked) {
      this.waitCheck.tableData.setOfCheckedId.add(id);
    } else {
      this.waitCheck.tableData.setOfCheckedId.delete(id);
    }
  }


  checkDevice(type: 'all' | 'current', id?: any) {
    if (type === 'all') {
      if (this.waitCheck.tableData.setOfCheckedId.size) {
        this.deviceCheckService.check(Array.from(this.waitCheck.tableData.setOfCheckedId).join(',')).then((res: any) => {
          if (res.code === 0) {
            this.nzMessageService.success('操作成功');
            this.waitCheck.tableData.checked = false;
            this.waitCheck.tableData.indeterminate = false;
            this.waitCheck.tableData.setOfCheckedId = new Set<number>();
            this.queryBtn('waitCheck');
            this.queryBtn('checked');
            this.queryBtn('statistics');
          } else {
            this.nzMessageService.error('操作失败');
          }
        });
      } else {
        this.nzMessageService.error('请选择要操作的数据');
      }
    } else if (type === 'current') {
      this.deviceCheckService.check(id).then((res: any) => {
        if (res.code === 0) {
          this.nzMessageService.success('操作成功');
          this.waitCheck.tableData.checked = false;
          this.waitCheck.tableData.indeterminate = false;
          this.waitCheck.tableData.setOfCheckedId = new Set<number>();
          this.queryBtn('waitCheck');
          this.queryBtn('checked');
          this.queryBtn('statistics');
        } else {
          this.nzMessageService.error('操作失败');
        }
      });
    }
  }

  // 查看设备详情
  showDeviceDetail(data: any) {
    this.deviceCheckService.getDeviceDetail(data.id).then((res: any) => {
      if (res.code === 0) {
        console.log(res);
        this.detailModal = {
          visible: true,
          id: data.id,
          phoneCode: res.data.phoneCode, // 机器编码
          net: res.data.net, // 网络制式
          typeName: res.data.typeName, // 品牌名
          modelName: res.data.modelName, // 机型名
          finalPrice: res.data.finalPrice, // 最终价格
          checkNote: res.data.checkNote, // 验机师备注
          store: res.data.store, // 存储容量
          colourName: res.data.colourName, // c端成色标识
          colourNameB: res.data.colourNameB, // b端成色标识
          img: res.data.img ? res.data.img.split(',') : [], // 图片
        };
      }
    });
  }

  hideDetailModal() {
    this.detailModal = {
      visible: false,
      id: '',
      phoneCode: '',
      net: '',
      typeName: '',
      modelName: '',
      finalPrice: '',
      checkNote: '',
      store: '',
      colourName: '',
      colourNameB: '',
      img: [],
    };
  }

  modalCheck() {
    this.checkDevice('current', this.detailModal.id);
    this.hideDetailModal();
    this.queryBtn('checked');
    this.queryBtn('statistics');
  }

  /**
   * ----------------------------------------------------------------
   * 修改库位 Modal
   * ----------------------------------------------------------------
   */
  showEditLocationModal(type: number) {
    if (!this.waitCheck.tableData.setOfCheckedId.size) {
      this.nzMessageService.warning('请先选择所需操作项');
      return;
    }

    this.locationModalObj.isMerge = type === 1 ? true : false;
    this.locationModalObj.libraryId = '';
    this.isKwVisible = true;
  }

  async submitLocationData() {
    if (!this.locationModalObj.libraryId) {
      this.nzMessageService.warning('请先选择库位');
      return;
    }


    if (this.locationModalObj.isMerge) {
      // 批量修改库位并二手占用
      let arrs = this.waitCheck.tableData.records
        .filter(el => this.waitCheck.tableData.setOfCheckedId.has(el['id']))
        .map((m: any) => {
          return m.equipmentCode;
        });
      let params = {
        equipmentCodeList: arrs.join(','),
        occupyStatus: 2,
        libraryId: this.locationModalObj.libraryId
      };
      const {code, data}: any = await this.usedStorePService.setSecondHandGoodsOccupy(params);
      this.isKwVisible = false;

      if (code === 0) {
        this.nzMessageService.success('操作成功');
        this.getWaitCheckTableList();
      }
    } else {
      // 批量修改库位
      let arrs = this.waitCheck.tableData.records
        .filter(el => this.waitCheck.tableData.setOfCheckedId.has(el['id']))
        .map((m: any) => {
          return {
            id: m.id,
            libraryId: this.locationModalObj.libraryId,
            equipmentCode: m.equipmentCode
          };
        });
      this.usedStorePService.changeDeviceLocation(arrs).then((res: any) => {
        this.isKwVisible = false;
        if (res.code === 0) {
          this.nzMessageService.success('操作成功');
          this.getWaitCheckTableList();
        }
      });
    }
  }

  // 批量二手占用
  secendOccupy() {
    if (!this.waitCheck.tableData.setOfCheckedId.size) {
      this.nzMessageService.warning('请先选择所需操作项');
      return;
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认将机器放到二手商城销售？',
      nzOnOk: async () => {
        let arrs = this.waitCheck.tableData.records
          .filter(el => this.waitCheck.tableData.setOfCheckedId.has(el['id']))
          .map((m: any) => {
            return m.equipmentCode;
          });
        let params = {
          equipmentCodeList: arrs.join(','),
          occupyStatus: 2
        };
        const {code, data}: any = await this.usedStorePService.setSecondHandGoodsOccupy(params);

        if (code === 0) {
          this.nzMessageService.success('操作成功');
          this.getWaitCheckTableList();
        }
      }
    });
  }
}
